﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Configuration.Install;
using System.ServiceModel;
using System.Configuration;
using KeywordDistributeInterface;

namespace KeywordDistributeService
{
    public partial class KeywordDistributteService : ServiceBase
    {
        ServiceHost host = new ServiceHost(typeof(ServiceImpl));

        public KeywordDistributteService()
        {
            InitializeComponent();

            this.ServiceName = "关键词分配服务";
        }

        protected override void OnStart(string[] args)
        {
            if (host != null && host.State == CommunicationState.Opened) host.Close();

            //参数获取设置的服务地址，如果没有，则保留默认的 127.0.0.1:8888
            string ip = ConfigurationSettings.AppSettings["ServiceIP"];
            int port = 8732;
            string uri = string.Format("net.tcp://{0}:{1}", ip, port);
            NetTcpBinding binding = new NetTcpBinding();
            binding.Security.Mode = SecurityMode.None;
            binding.ReceiveTimeout = TimeSpan.MaxValue;//设置连接自动断开的空闲时长；

            host.AddServiceEndpoint(typeof(IKeywordDistribute), binding, uri);
            //MessageCenter.Instance.ListenerAdded += new EventHandler<MessageListenerEventArgs>(Instance_ListenerAdded);
            //MessageCenter.Instance.ListenerRemoved += new EventHandler<MessageListenerEventArgs>(Instance_ListenerRemoved);
            host.Open();
        }

        protected override void OnStop()
        {
            if (host != null)
                host.Close();
            host = null;
        }
    }

    [RunInstaller(true)]
    public class ProjectInstaller : Installer
    {
        private ServiceProcessInstaller process;
        private ServiceInstaller service;

        public ProjectInstaller()
        {
            process = new ServiceProcessInstaller();
            process.Account = ServiceAccount.NetworkService;
            service = new ServiceInstaller();
            service.StartType = ServiceStartMode.Automatic;
            service.ServiceName = "关键词分配服务";
            Installers.Add(process);
            Installers.Add(service);
        }
    }
}
